﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Wuqi.Webdiyer;

namespace ZWZ.Web.WebAdmin
{
    public partial class umsg : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                CtrList1.Columns = new List<UCtrs.ListColumn>() { 
                     new UCtrs.ListColumn(){ Caption="用户",FieldName="UserName", Width="100px",OnClientClick="ViewMessage('{0}');"},
                     new UCtrs.ListColumn(){ Caption="内容", FieldName="Title", Style="text-align:left;",OnClientClick="ViewMessage('{0}');"},
                     new UCtrs.ListColumn(){ Caption="时间", FieldName="SentTime",Width="120px", DataFormat="{0:yyyy-MM-dd HH:mm}"}
                };
                BindData();
            }
        }
        protected void CtrList_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "Delete")
            {
                string id = e.CommandArgument.ToString();
                var oldmodel = DBProvider.DB.Ctx.User_Group.Where(i => i.ID == id).FirstOrDefault();
                if (oldmodel != null)
                {
                    DBProvider.DB.Ctx.User_Group.DeleteObject(oldmodel);
                    DBProvider.DB.Ctx.SaveChanges();
                }
                BindData();
            }
        }
        protected void CtrList_PageChanging(object src, PageChangingEventArgs e)
        {
            CtrList1.CurrentPageIndex = e.NewPageIndex;
            BindData();
        }
        protected void BindData()
        {
            var CurrentUser = Codes.LoginHelper.CurrentUser;
            var BDData = DBProvider.DB.Ctx.User_Message
                .Where(arg => (arg.ReciverID == CurrentUser.ID || arg.SenderID == CurrentUser.ID))
                .Select((arg) => new
                        {
                            arg.ID,
                            UserID = (arg.SenderID == CurrentUser.ID ? arg.ReciverID : arg.SenderID),
                            UserName = (arg.SenderID == CurrentUser.ID ? arg.ReciverName : arg.SenderName),
                            arg.Title,
                            arg.Body,
                            arg.SentTime,
                        })
                .GroupBy(arg => arg.UserID);
            CtrList1.RecordCount = BDData.Count();
            CtrList1.DataSource = BDData
                .Select(arg=>arg.OrderByDescending(i=>i.SentTime).FirstOrDefault())
                .OrderByDescending(arg => arg.SentTime)
                .Skip((CtrList1.CurrentPageIndex - 1) * CtrList1.PageSize)
                .Take(CtrList1.PageSize)
                .ToList();
            CtrList1.DataBind();
        }
    }
}